package com.xyh.common.exception;

import com.xyh.common.util.ResultCode;
import com.xyh.common.util.ResultVO;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author:kyle
 * @Date:2021/1/5 - 11:42
 * @Project:shirodemo
 * @Package:com.xyh.common.config
 * @Version:1.0 自定义全局异常捕获
 */
//@ControllerAdvice这是一个增强的 Controller。
//使用这个 Controller ，可以实现三个方面的功能：
//全局异常处理
//全局数据绑定
//全局数据预处理
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 自定义异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizRuntimeException.class)
    @ResponseBody
    public ResultVO bizExceptionHandler(HttpServletRequest request, BizRuntimeException e) {
        log.error("发生业务异常，原因是:" + e.getMessage());
        return ResultVO.fail(e.getStatus(), e.getMessage());
    }

    /**
     * 空指针异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultVO nullPointerException(HttpServletRequest request, NullPointerException e) {

        log.error("空指针异常：" + e);
        return ResultVO.fail(ResultCode.BODY_NOT_MATCH);
    }

    /**
     * 账户不存异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = UnknownAccountException.class)
    @ResponseBody
    public ResultVO unknownAccountExceptionHandler(HttpServletRequest request, UnknownAccountException e) {

        log.error("账户不存异常：" + e);
        return ResultVO.fail(ResultCode.USER_NOT_EXIST);
    }

    /**
     * 处理密码不匹配的异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = IncorrectCredentialsException.class)
    @ResponseBody
    public ResultVO incorrectCredentialsExceptionHandler(HttpServletRequest request, IncorrectCredentialsException e) {
        log.error("密码不匹配的异常！原因是:", e);
        return ResultVO.fail(ResultCode.USER_PASS_ERROR);
    }

    /**
     * 处理其他异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultVO exceptionHandler(HttpServletRequest request, Exception e) {
        log.error("未知异常！原因是:", e);
        System.out.println("e = " + e);
        return ResultVO.fail(ResultCode.INTERNAL_SERVER_ERROR);
    }

}
